import {
  getUserInfo,
  setUserInfo
} from '../../utils/store';
import api from "../../utils/apiInstance"
Page({

  /**
   * 页面的初始数据
   */
  data: {
    id: null,
    detail: {},
    deptList: [],
    illegalDate: new Date().toISOString().substring(0, 10),
    bigSearchShow: false,
    bigSearchType: "",
    searchDataList: [],
    dept: '',
    safersIndex: null,
    safersIndex2: null
  },
  async getAllDept() {
    var that = this;
    let res = await api.get(`/deptInfo/wx/getAllDept`);
    console.log('获取所有部门信息:', res.data);
    that.setData({
      deptList: res.data
    })
  },

  async getDetail (id) {
    var that = this;
    let res = await api.get(`/punishTicket/wx/`+id);
    console.log('处罚通知单详情:', res);
    that.setData({
      detail: res.data,
      illegalDate: res.data.punishDate,
      dept: res.data.dept
    })
  },

  async submitForm(e) {
    var that = this;
    const formData = e.detail.value;
    formData.dept = that.data.dept;
    formData.createBy = getUserInfo().siocSapNo;
    formData.excutor = getUserInfo().siocCnName;
    console.log('form发生了submit事件，携带数据为：', formData);
    var errMsg = "";
    if (!formData.unitName) {
      errMsg = errMsg + "单位名称不能为空;";
    }
    // if (!formData.punishDate) {
    //   errMsg = errMsg + "日期不能为空;";
    // }
    if (!formData.location) {
      errMsg = errMsg + "地点不能为空;";
    }
    if (!formData.parties) {
      errMsg = errMsg + "当事人不能为空;";
    }
    // if (!formData.partyNo) {
    //   errMsg = errMsg + "当事人电话不能为空;";
    // }
    if (!formData.unitManager) {
      errMsg = errMsg + "单位负责人不能为空;";
    }
    if (!formData.unitManagerNo) {
      errMsg = errMsg + "单位负责人电话不能为空;";
    }
    if (!formData.dept) {
      errMsg = errMsg + "责任部门不能为空;";
    }
    if (!formData.incidentDescription) {
      errMsg = errMsg + "事由描述不能为空;";
    }
    if (!formData.punishMeasure) {
      errMsg = errMsg + "处罚措施不能为空;";
    }
    if (errMsg.length > 0) {
      wx.showModal({
        title: '提示',
        content: errMsg,
        showCancel: false
      })
      return;
    }
    // 向服务器提交表单数据
    let res = await api.post(`/punishTicket/wx/add`,formData);
    console.log('表单提交成功', res);
    if (200 == res.code) {
      wx.showModal({
        title: '提示',
        content: res.msg,
        showCancel: false,
        success: function (res) {
          if (res.confirm) {
            wx.reLaunch({
              url: '/pages/punish-list/punish-list'
            })
          }
        }
      })
    } else {
      wx.showToast({
        title: res.msg,
        icon: 'none'
      });
    }
  },

  async getSafers () {
    var that = this;
    let res = await api.get(`/staffInfo/wx/getStaffInfoByDept?dept=应急管理部`);
    console.log('获取安全部人员:', res);
    that.setData({
      safers: res.data
    })
  },

  DateChange: function (e) {
    this.setData({
      illegalDate: e.detail.value
    })
  },

  doBigSearchShow(e) {
    const that = this
    console.log('e', this.data);
    const tempArray = [];
    const typeMethods = {
      dept: () => {
        if (that.data.deptList.length == 0) {
          wx.showToast({
            title: '暂无部门',
            icon: 'none'
          });
          return;
        } else {
          that.data.deptList.forEach(item => {
            tempArray.push({
              name: item
            });
          });
        }
      }
    }
    typeMethods[e.currentTarget.dataset.type]();

    this.setData({
      bigSearchType: e.currentTarget.dataset.type,
      bigSearchShow: true,
      searchDataList: tempArray
    })
  },
  searchSelect(e) {
    const params = {}
    params['dept'] = e.detail.name

    this.setData({
      ...params
    })
  },
  ViewImage(e) {
    wx.previewImage({
      urls: this.data.imgList,
      current: e.currentTarget.dataset.url
    });
  },
  DelImg(e) {
    wx.showModal({
      title: '删除图片',
      content: '确定要删除这张图片',
      cancelText: '取消',
      confirmText: '确定',
      success: res => {
        if (res.confirm) {
          this.data.imgList.splice(e.currentTarget.dataset.index, 1);
          this.setData({
            imgList: this.data.imgList
          })
        }
      }
    })
  },
  ChooseImage: function () {
    var that = this;
    wx.chooseMedia({
      count: 1, // 一次只能选择一张图片
      sizeType: ['original', 'compressed'], // 压缩图片
      sourceType: ['album', 'camera'], // 从相册选择
      success(res) { // 将图片上传到服务器
        wx.uploadFile({
          url: that.data.fileUrl + '/common/picUpload', // 上传的服务器地址
          filePath: res.tempFiles[0].tempFilePath, // 图片的本地地址
          name: 'file', // 服务端用于接收文件的参数名
          success(res) {
            let json = JSON.parse(res.data);
            let tempArray = [];
            tempArray.push(json.fileName);
            // 上传成功，做一些处理
            if (that.data.imgList.length != 0) {
              that.setData({
                imgList: that.data.imgList.concat(tempArray)
              })
            } else {
              that.setData({
                imgList: tempArray
              })
            }
          }
        })
      }
    })
  },

  equipmentTypeSearchSelect(e) {

    if (e.detail.length > 0) {
      const tempArray = []
      const tempArray1 = []
      e.detail.forEach(item => {
        tempArray.push(this.data.typeArray.findIndex((subitem) => subitem == item.name))
        tempArray1.push(item.name)
      })

      this.setData({
        equipmentType: tempArray.join(','),

        typeArrayName: tempArray1.join(',')
      })
    }
    // const params = {}
    // params['convenerDept'] = e.detail.name

    // this.setData({
    //   ...params
    // })
  },

  saferChange (e) {
    this.setData({
      safersIndex: e.detail.value
    })
  },

  saferChange2 (e) {
    this.setData({
      safersIndex2: e.detail.value
    })
  },


  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    console.log('options', options);
    if (options.id) {
      this.getDetail(options.id);
      this.setData({
        id: options.id
      });
    }else{
      this.getAllDept();
      this.getSafers();
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})